﻿using System;
using System.Linq;
using DDDSample.Application.Repositories;
using DDDSample.Domain.Cargo;
using DDDSample.Domain.HandlingEvent;
using DDDSample.Domain.Location;
using NHibernate;
using NHibernate.Linq;

namespace DDDSample.Application.HandlingEvent
{
    public class HandlingEventService : IHandlingEventService
    {
        private readonly ISession _session;

        public HandlingEventService(ISession session)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }
            _session = session;
        }

        public Guid Store(Domain.HandlingEvent.HandlingEvent handlingEvent)
        {
            return (Guid)_session.Save(handlingEvent);
        }

        public HandlingHistory LookupHandlingHistoryOfCargo(Guid cargoId)
        {
            var events = _session.Query<Domain.HandlingEvent.HandlingEvent>().Where(e => e.Cargo.Id == cargoId).ToList();
            return new HandlingHistory(events);
        }

        public void RegisterHandlingEvent(DateTime completionTime, Guid cargoId, UnLocode unLocode, HandlingEventType type)
        {
            var cargo = _session.Get<Cargo>(cargoId);
            var location = _session.FindLocation(unLocode);
            var @event = new Domain.HandlingEvent.HandlingEvent(type, location, DateTime.Now, completionTime, cargo);
            var id = (Guid)_session.Save(@event);
            _session.Flush();
        }
    }
}